package com.gk.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gk.bean.GuoYaoBackDto.ZxyStockadjustGuoyao;
import com.gk.bean.GuoYaoBackDto.ZxyZlyhjlGuoyao;
import com.gk.bean.qfEntity.GoodsStocks;
import com.gk.bean.qfEntity.Ptype_qf;
import com.gk.bean.qfEntity.ZxyErrorinfo;
import com.gk.bean.qfPro.*;
import com.gk.bean.qfQueryInfo.GoodsStocksQuery;
import com.gk.bean.qfdto.GKT400BackJson;
import com.gk.dao.*;
import com.gk.http.entity.HttpResult;
import com.gk.http.service.GetGkDataService;
import com.gk.service.OtherBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

@Service
@Slf4j
public class OtherBillServiceImpl implements OtherBillService {
    @Resource
    private GetGkDataService getGkDataService;
    @Resource
    private ZxyStockadjustGuoyaoDao zxyStockadjustGuoyaoDao;

    @Override
    public void AddGuoYaoStockAdjustBillToQF(String str) {
        HttpResult gkStockAdjustData;
        if (!str.equals("")) {
            gkStockAdjustData = JSON.parseObject(str, HttpResult.class);
        } else {
            gkStockAdjustData = getGkDataService.getGkStockAdjustData();
        }
        if (gkStockAdjustData.getCode().equals("0")) {
            List<GKT400BackJson> gkt400BackJsons = JSONArray.parseArray(gkStockAdjustData.getData(), GKT400BackJson.class);
            for (GKT400BackJson gkt400BackJson : gkt400BackJsons) {
                List<ZxyStockadjustGuoyao> zxyStockadjustGuoyaos = JSONArray.parseArray(JSON.toJSONString(gkt400BackJson.getXml().getContent().getDetail().getSub().getSubline()), ZxyStockadjustGuoyao.class);
                for (ZxyStockadjustGuoyao zxyStockadjustGuoyao : zxyStockadjustGuoyaos) {
                    int i = zxyStockadjustGuoyaoDao.insertSelective(zxyStockadjustGuoyao);
                    log.info("插入库存调整单到千方,影响行数:" + i);
                }
            }
            //TODO 获取好数据以后,调用插入接口
            this.CreateQFBatchnoChangeBill();
            this.CreateQFStopSaleBill();
        } else {
            log.info("暂时未能拉取到国药库存调整单！");
        }
    }

    @Value("${qf.common.kuserCode}")
    private String kuserCode;
    @Resource
    private GoodsStocksDao goodsStocksDao;
    @Resource
    private BatchNoBillDao batchNoBillDao;

    @Override
    public void CreateQFBatchnoChangeBill() {
        List<ZxyStockadjustGuoyao> guoYaoStockAdjustList = zxyStockadjustGuoyaoDao.getGuoYaoStockAdjustBatchnoChangeList("");
        int krec = 0;
        for (ZxyStockadjustGuoyao stockadjustGuoyao : guoYaoStockAdjustList) {
            GoodsStocksQuery stocksQuery = new GoodsStocksQuery();
            //拼接查询条件
            stocksQuery.setPrec(Integer.parseInt(stockadjustGuoyao.getOwnergoodsid()))
                    .setJobNumber(stockadjustGuoyao.getFromlotno())
                    .setOutFactoryDate(stockadjustGuoyao.getFromproddate())
                    .setValidityPeriod(stockadjustGuoyao.getFromvaliddate())
                    .setKuserCode(kuserCode)
                    .setQty(stockadjustGuoyao.getQty());
            //开始检索库存是否存在
            GoodsStocks goodsstocks = goodsStocksDao.getGoodsStocksUniqueid(stocksQuery);
            if (goodsstocks == null) {
                log.error("当前库存无法检索当国药生成的库存调整单数量(批号调整单)" + JSON.toJSONString(stockadjustGuoyao));
                return;
            }
            krec = goodsstocks.getKrec();
            //TODO ==================================================检索到数据,开始生成单据======================================
            //TODO 插入主数据开始
            Gp_InsertBillIndex billIndex = new Gp_InsertBillIndex();
            billIndex.setBillDate(DateUtil.today())
                    .setBillCode(stockadjustGuoyao.getBillno() + "-" + stockadjustGuoyao.getId())
                    .setBillType(404)
                    .setBREc(0)
                    .setERec(0)
                    .setKRec(krec)
                    .setTotalMoney(0.0)
                    .setTotalQty(stockadjustGuoyao.getQty())
                    .setComment("根据wms批号调整单,自动生成批号修改单>>" + stockadjustGuoyao.getBillno())
                    .setInvoice("");
            int billId = batchNoBillDao.addBatchNoUpdateBillIndex(billIndex);
            //TODO 开始插入明细数据
            if (billId > 0) {
                GP_InsertAdjustJobBill batchNoDetails = new GP_InsertAdjustJobBill();
                batchNoDetails.setBillId(billId)
                        .setPrec(Integer.parseInt(stockadjustGuoyao.getOwnergoodsid()))
                        .setKrec(goodsstocks.getKrec())
                        .setUnit(1)
                        .setQty(stockadjustGuoyao.getQty())
                        .setPrice(goodsstocks.getPrice())
                        .setOldJobNumber(stockadjustGuoyao.getFromlotno())
                        .setOldOutFactoryDate(stockadjustGuoyao.getFromproddate())
                        .setOldValidityPeriod(stockadjustGuoyao.getFromvaliddate())
                        .setNewJobNumber(stockadjustGuoyao.getTolotno())
                        .setNewOutFactoryDate(stockadjustGuoyao.getToproddate())
                        .setNewValidityPeriod(stockadjustGuoyao.getTovaliddate())
                        .setComment("根据wms批号调整单,自动生成单据")//存储wms 的批号修改单据id
                        .setOrd(1)
                        .setProviderId(goodsstocks.getProviderid())
                        .setPtypeSource(0)
                        .setGrec(0)
                        .setStockUniqueid(goodsstocks.getStockuniqueid())
                        .setStockUniqueid2(null)
                        .setOldJobCode(goodsstocks.getJobcode())
                        .setNewJobCode(goodsstocks.getJobcode())
                        .setStopUse(0)
                        .setOldGermJobNumber(goodsstocks.getGermjobnumber())
                        .setNewGermJobNumber(goodsstocks.getGermjobnumber())
                        .setOldCheckReportNo(goodsstocks.getCheckreportno())
                        .setNewCheckReportNo(goodsstocks.getCheckreportno())
                        .setOldGJobId(0)
                        .setNewGJobId(0);
                batchNoBillDao.addBatchNoUpdateBillDetails(batchNoDetails);
                //TODO 生成单据成功后,将flags标识符改成1
                int row = zxyStockadjustGuoyaoDao.updateFlagsById(stockadjustGuoyao.getId());
            }
        }
    }

    @Resource
    private PtypeDao ptypeDao;
    @Resource
    private OtherBillDao otherBillDao;

    @Override
    public void CreateQFStopSaleBill() {
        List<ZxyStockadjustGuoyao> guoYaoStockAdjustList = zxyStockadjustGuoyaoDao.getGuoYaoStockAdjustStopSaleList("");
        int krec = 0;
        for (ZxyStockadjustGuoyao stockadjustGuoyao : guoYaoStockAdjustList) {
            GoodsStocksQuery stocksQuery = new GoodsStocksQuery();
            //拼接查询条件
            stocksQuery.setPrec(Integer.parseInt(stockadjustGuoyao.getOwnergoodsid()))
                    .setJobNumber(stockadjustGuoyao.getFromlotno())
                    .setOutFactoryDate(stockadjustGuoyao.getFromproddate())
                    .setValidityPeriod(stockadjustGuoyao.getFromvaliddate())
                    .setKuserCode(kuserCode)
                    .setQty(stockadjustGuoyao.getQty());
            //开始检索库存是否存在
            GoodsStocks goodsstocks = goodsStocksDao.getGoodsStocksUniqueid(stocksQuery);
            if (goodsstocks == null) {
                log.error("当前库存无法检索当国药生成的库存调整单数量(状态异常商品)" + JSON.toJSONString(stockadjustGuoyao));
                return;
            }
            krec = goodsstocks.getKrec();
            //TODO ==================================================检索到数据,开始生成单据======================================
            Ptype_qf ptype_qf = ptypeDao.getPtypeQfEntityByRec(Integer.parseInt(stockadjustGuoyao.getOwnergoodsid()));
            if (ptype_qf == null) {
                log.error("千方不存在当前商品信息(状态异常商品)" + JSON.toJSONString(stockadjustGuoyao));
            }
            Gspzgb_Pstopsale pstopsale = new Gspzgb_Pstopsale();
            for (ZxyStockadjustGuoyao zxyStockadjustGuoyao : guoYaoStockAdjustList) {
                pstopsale
                        .setSzNumber(zxyStockadjustGuoyao.getBillno())
                        .setSzPtypeId(ptype_qf.getTypeId())
                        .setSzPFullname(ptype_qf.getFullName())
                        .setSzStandard(ptype_qf.getStandard())
                        .setSzProduce(ptype_qf.getProduceName())
                        .setSzUnit(ptype_qf.getUnit1Name())
                        .setDQty(zxyStockadjustGuoyao.getTradegoodsqty())
                        .setSzJobnumber(goodsstocks.getJobnumber())
                        .setSzCheckResult("根据反馈Wms自动生成数据")
                        .setSzDeal("")
                        .setProducedate(stockadjustGuoyao.getFromproddate())
                        .setValidate(stockadjustGuoyao.getFromvaliddate())
                        .setDate(LocalDate.now().toString())
                        .setSzAddress(goodsstocks.getStockName())
                        .setSzDepartmente("")
                        .setSzEFullname("")
                        .setKfypeId(goodsstocks.getStockTypeId())
                        .setKfullname(goodsstocks.getStockName())
                        .setPrice(goodsstocks.getPrice())
                        .setProviderId(goodsstocks.getProviderid() + "")
                        .setSzBhgKtypeid("99999")
                        .setStockUniqueid(goodsstocks.getStockuniqueid())
                        .setJobcode(goodsstocks.getJobcode())
                        .setGermJobNumber(goodsstocks.getGermjobnumber())
                        .setCheckReportNo(goodsstocks.getCheckreportno())
                        .setPrec(goodsstocks.getPrec());
                int i = otherBillDao.addGoodsStopSaleBill(pstopsale);
                //TODO 生成单据成功后,将flags标识符改成1
                int row = zxyStockadjustGuoyaoDao.updateFlagsById(stockadjustGuoyao.getId());
                log.error("自动生成的停售单草稿nOrder=" + i);
            }
        }
    }

    @Resource
    private ZxyZlyhjlGuoyaoDao zxyZlyhjlGuoyaoDao;

    @Override
    public void CreateQFYHMaintainRecord() {
        //TODO 首先获取国药返回的数据(去重单号)
        List<String> billCodeList = zxyZlyhjlGuoyaoDao.getDistinctZlyhjlGuoyaoBillCode(0);
        //TODO  首先获取国药返回的详细数据并且生成养护记录
        for (String billCode : billCodeList) {
            int billId = 0;
            List<ZxyZlyhjlGuoyao> guoYaoZlyhjlList = zxyZlyhjlGuoyaoDao.getGuoYaoZlyhjlList(billCode);
            if (checkStocks(guoYaoZlyhjlList)) {
                for (int i = 0; i < guoYaoZlyhjlList.size(); i++) {
                    ZxyZlyhjlGuoyao zxyZlyhjlGuoyao = guoYaoZlyhjlList.get(i);
                    if (i == 0) {
                        billId = 0;
                        //如果是第一次执行,要进行插入养护记录主表
                        Z_InsertMaintainIndex z_insertMaintainIndex = new Z_InsertMaintainIndex();
                        z_insertMaintainIndex
                                .setBillId(0)
                                .setBillCode(zxyZlyhjlGuoyao.getOrderNbr())
                                .setBillDate(zxyZlyhjlGuoyao.getCrtDate())
                                .setKrec(goodsStocksDao.getStockRecByCode(kuserCode))
                                .setYhType(zxyZlyhjlGuoyao.getOrderType().equals("一般养护") ? 0 : 1)
                                .setErec(0)
                                .setMaintainUser(zxyZlyhjlGuoyao.getOprtPerson1())
                                .setChecked(0).setChecker(0);
                        billId = otherBillDao.z_InsertMaintainIndex(z_insertMaintainIndex);
                    }
                    if (billId > 0) {
                        GoodsStocksQuery query = new GoodsStocksQuery();
                        //获取当前批号商品的库存信息
                        query.setPrec(Integer.parseInt(zxyZlyhjlGuoyao.getItemCode4Cms()))
                                .setJobNumber(zxyZlyhjlGuoyao.getBatchNbr())
                                .setOutFactoryDate(zxyZlyhjlGuoyao.getPartyMfrDate())
                                .setValidityPeriod(zxyZlyhjlGuoyao.getExpireDate())
                                .setKuserCode(kuserCode);
                        List<GoodsStocks> goodsstocksList = goodsStocksDao.getGoodsStocksUniqueidNoQty(query);
                        //TODO 根据库存信息生成养护数据
                        for (GoodsStocks goodsStocks : goodsstocksList) {
                            Z_InsertMaintainBill z_insertMaintainBill = new Z_InsertMaintainBill();
                            z_insertMaintainBill.setBillId(billId)
                                    .setOrd(i + 1).
                                    setPrec(goodsStocks.getPrec())
                                    .setKrec(goodsStocks.getKrec())
                                    .setGrec(goodsStocks.getGrec())
                                    .setQty(goodsStocks.getQty())
                                    .setProviderId(goodsStocks.getProviderid())
                                    .setOutFactoryDate(goodsStocks.getOutfactorydate())
                                    .setJobNumber(goodsStocks.getJobnumber())
                                    .setValidityPeriod(goodsStocks.getValidityperiod())
                                    .setJobCode(goodsStocks.getJobcode())
                                    .setGermJobNumber(goodsStocks.getGermjobnumber())
                                    .setCheckReportNo(goodsStocks.getCheckreportno())
                                    .setIntime(goodsStocks.getIntime())
                                    .setLastmaintainTime(goodsStocks.getLastmaintaintime())
                                    .setQualitystatus(zxyZlyhjlGuoyao.getOprtResult().equals("Y") ? "无异常" : "异常")
                                    .setMeasures("")
                                    .setSuggestion("")
                                    .setStopSale(0)
                                    .setComment("由三方自动生成养护数据")
                                    .setStockUniqueid(goodsStocks.getStockuniqueid())
                                    .setGoodsId(goodsStocks.getGoodsid())
                                    .setGjobId(goodsStocks.getGjobid());
                            int mxCount = otherBillDao.Z_InsertMaintainBill(z_insertMaintainBill);
                        }
                    } else {
                        ZxyErrorinfo zxyErrorinfo = new ZxyErrorinfo();
                        zxyErrorinfo.setTablename("Z_InsertMaintainIndex")
                                .setErrorreason(JSON.toJSONString(zxyZlyhjlGuoyao) + "创建千方养护记录失败")
                                .setErrormessage("OtherBillServiceImpl.CreateQFYHMaintainRecord.Z_InsertMaintainIndex");
                        zxyErrorinfoDao.insertSelective(zxyErrorinfo);
                    }
                }
                //TODO 生成养护记录以后,关闭单据
                zxyZlyhjlGuoyaoDao.closeGuoYaoZlyhjl(billCode);
            } else {
                log.error("生成养护记录执行,但未自动生成千方的养护记录,具体原因请看日志记录表");
            }
        }
    }

    @Resource
    private ZxyErrorinfoDao zxyErrorinfoDao;

    //TODO 检索库存是否满足,如果不满足则不生成养护记录
    public boolean checkStocks(List<ZxyZlyhjlGuoyao> zxyZlyhjlGuoyaos) {
        boolean _result = true;
        for (ZxyZlyhjlGuoyao zxyZlyhjlGuoyao : zxyZlyhjlGuoyaos) {
            GoodsStocksQuery query = new GoodsStocksQuery();
            //拼接查询条件
            query.setPrec(Integer.parseInt(zxyZlyhjlGuoyao.getItemCode4Cms()))
                    .setJobNumber(zxyZlyhjlGuoyao.getBatchNbr())
                    .setOutFactoryDate(zxyZlyhjlGuoyao.getPartyMfrDate())
                    .setValidityPeriod(zxyZlyhjlGuoyao.getExpireDate())
                    .setKuserCode(kuserCode);
            List<GoodsStocks> goodsstocks = goodsStocksDao.getGoodsStocksUniqueidNoQty(query);
            if (CollUtil.isEmpty(goodsstocks)) {
                ZxyErrorinfo zxyErrorinfo = new ZxyErrorinfo();
                zxyErrorinfo.setTablename("zxy_zlyhjl_guoyao")
                        .setErrorreason(JSON.toJSONString(zxyZlyhjlGuoyao) + "商品库存信息在千方数据库存表中未找到,千方的查询条件为:" + JSON.toJSONString(query))
                        .setErrormessage("OtherBillServiceImpl.checkStocks");
                zxyErrorinfoDao.insertSelective(zxyErrorinfo);
                _result = false;
            }
        }
        return _result;
    }
}
